Tengo una función como esta:
function toggle(me, style) { var myelm = me == '' ? this : document.getElementById(me); myelm.classList = style; }Quiero que la función sepa cuándo tiene que aplicar el estilo al elemento desencadenante o a algún otro elemento como en los siguientes ejemplos:
<div onclick="toggle(this);"></div> <!--this function should apply to this element only--> <div onclick="toggle('otherelement');"></div> <!--this should apply to other element of the DOM--> pero solo funciona cuando se especifica la ID, y no se aplicará como this esperaba. ¿Qué está mal?
En el primer caso, pasa un elemento DOM, en el segundo, una cadena (no vacía). Entonces, la condición me == '' que verifica no es cierta en ninguno de los casos. En segundo lugar, this es irrelevante en la función, ya que nunca se llama con un enlace this (un enlace this no es lo mismo que pasar this como argumento).
Querrá verificar el tipo de datos del argumento, y cuando sea una cadena, recuperar el elemento DOM y, de lo contrario, simplemente usar el argumento que se le dio ( me ), no this :
Otra cosa: debe llamar al método de toggle en la propiedad classList :
function toggle(me, style) { var myelm = typeof me != 'string' ? me : document.getElementById(me); myelm.classList.toggle(style); }NB: ¡asegúrate de pasar también el segundo argumento (estilo)!
Retazo:
function toggle(me, style) { var myelm = typeof me != 'string' ? me : document.getElementById(me); myelm.classList.toggle(style); } .highlight { background: yellow } <div id="otherelement">This is other element</div> <p></p> <div onclick="toggle(this, 'highlight');">toggle this</div> <div onclick="toggle('otherelement', 'highlight');">toggle other element</div>